﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO;
using System.Collections;
using System.Xml;

namespace ContentMigrator
{
    public partial class frmNewDB : Form
    {
        public frmNewDB()
        {
            InitializeComponent();
        }
        #region EVENT HANDLERS
        void lstFiles_DragOver(object sender, System.Windows.Forms.DragEventArgs e)
        {
            e.Effect = DragDropEffects.Copy;
        }
        void lstFiles_DragDrop(object sender, System.Windows.Forms.DragEventArgs e)
        {
            try
            {
                if (e.Data.GetDataPresent("FileDrop"))
                {
                    string[] files = (string[])e.Data.GetData("FileDrop");
                    foreach (string myitem in files)
                        if (Directory.Exists(myitem))
                        {
                            ArrayList arl = new ArrayList();
                            StaticMethods.ExpandFolderToArrayList(myitem, arl);
                            foreach (string myfile in arl)
                            {
                                if (!lstFiles.Items.Contains(myfile))
                                    lstFiles.Items.Add(myfile);
                            }
                        }
                        else
                            if (File.Exists(myitem))
                                if (!lstFiles.Items.Contains(myitem))
                                    lstFiles.Items.Add(myitem);
                }
                ResizeListColumns(lstFiles);
                lblCount.Text = lstFiles.Items.Count.ToString() + " items";
            }
            catch (Exception ex)
            {

                throw new Exception("Drag/drop error: " + ex.Message);
            }
        }
        private void btnClose_Click(object sender, EventArgs e)
        {
            this.Close();
        }
        private void btnAddFile_Click(object sender, EventArgs e)
        {
            try
            {
                OpenFileDialog ofd = new OpenFileDialog();
                ofd.Multiselect = true;
                ofd.InitialDirectory = "C:\\";
                ofd.ShowDialog();

                if (ofd.FileNames.Length > 0)
                    foreach (string myfile in ofd.FileNames)
                    {
                        if (!lstFiles.Items.Contains(myfile))
                            lstFiles.Items.Add(myfile);
                    }
                ResizeListColumns(lstFiles);
                lblCount.Text = lstFiles.Items.Count.ToString() + " items";
            }
            catch (Exception ex)
            {

                MessageBox.Show(ex.Message, "ERROR", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
        private void btnAddFolder_Click(object sender, EventArgs e)
        {
            try
            {
                FolderBrowserDialog fbd = new FolderBrowserDialog();
                fbd.RootFolder = Environment.SpecialFolder.MyComputer;
                fbd.ShowDialog();

                if (fbd.SelectedPath != string.Empty)
                {
                    ArrayList files = new ArrayList();
                    StaticMethods.ExpandFolderToArrayList(fbd.SelectedPath, files);
                    foreach (string myfile in files)
                    {
                        if (!lstFiles.Items.Contains(myfile))
                            lstFiles.Items.Add(myfile);
                    }
                    ResizeListColumns(lstFiles);
                    lblCount.Text = lstFiles.Items.Count.ToString() + " items";
                }
            }
            catch (Exception ex)
            {

                MessageBox.Show("Error adding folder: " + ex.Message);
            }
        }
        private void btnRemove_Click(object sender, EventArgs e)
        {
            try
            {
                if (lstFiles.SelectedIndices.Count > 0)
                {
                    foreach (int myidx in lstFiles.SelectedIndices)
                    {
                        lstFiles.Items.RemoveAt(myidx);
                    }
                    ResizeListColumns(lstFiles);
                    lblCount.Text = lstFiles.Items.Count.ToString() + " items";
                }
            }
            catch (Exception ex)
            {

                MessageBox.Show("Error removing list item(s): " + ex.Message);
            }
        }
        private void btnClear_Click(object sender, EventArgs e)
        {
            if (lstFiles.Items.Count > 0)
            {
                lstFiles.Items.Clear();
                ResizeListColumns(lstFiles);
                lblCount.Text = lstFiles.Items.Count.ToString() + " items";
            }
        }
        private void btnCreateBlank_Click(object sender, EventArgs e)
        {
            try
            {
                SaveFileDialog sd = new SaveFileDialog();
                sd.InitialDirectory = "C:\\";
                sd.ShowDialog();

                if (sd.FileName != string.Empty)
                {
                    CreateBlankDB(sd.FileName);
                    if (StaticMethods.frmLoadMetabase1 != null)
                        StaticMethods.frmLoadMetabase1.Close();

                    StaticMethods.frmLoadMetabase1 = new frmLoadMetabase(sd.FileName);
                    StaticMethods.frmLoadMetabase1.MdiParent = StaticMethods.frmMainRef;
                    StaticMethods.frmLoadMetabase1.Icon = this.Icon;

                    StaticMethods.frmLoadMetabase1.Show();
                    this.Close();
                }
            }
            catch (Exception ex)
            {
                
                MessageBox.Show(ex.Message,"ERROR", MessageBoxButtons.OK,MessageBoxIcon.Error);
            }
        }
        private void btnCreateFile_Click(object sender, EventArgs e)
        {
            SaveFileDialog sd = new SaveFileDialog();
            sd.InitialDirectory = "C:\\";
            sd.ShowDialog();
            if (sd.FileName != string.Empty && lstFiles.Items.Count > 0)
            {
                CreateDBFromList(lstFiles, "Filename",sd.FileName);
                if (StaticMethods.frmLoadMetabase1 != null)
                    StaticMethods.frmLoadMetabase1.Close();

                StaticMethods.frmLoadMetabase1 = new frmLoadMetabase(sd.FileName);
                StaticMethods.frmLoadMetabase1.MdiParent = StaticMethods.frmMainRef;
                StaticMethods.frmLoadMetabase1.Icon = this.Icon;
                StaticMethods.frmLoadMetabase1.Show();
                this.Close();
            }

        }
        #endregion
        #region METHODS
        private float MeasureStringWidth(string Text, string FontName, float FontSize)
        {
            Bitmap b;
            Graphics g;
            Font f = new Font(FontName, FontSize);

            //Compute the string dimensions in the given font
            b = new Bitmap(1, 1, System.Drawing.Imaging.PixelFormat.Format32bppArgb);
            g = Graphics.FromImage(b);
            SizeF stringSize = g.MeasureString(Text, f);
            g.Dispose();
            b.Dispose();
            return stringSize.Width;
        }
        private void ResizeListColumns(ListBox mylist)
        {
            try
            {
                //Resize column width to widest item
                int maxsize = 0;
                //const float COL_SPACING = 5;
                string text = string.Empty;
                foreach (object myitem in mylist.Items)
                {
                    if (myitem.ToString().Length > maxsize)
                    {
                        maxsize = myitem.ToString().Length;
                        text = myitem.ToString();
                    }
                }

                lstFiles.ColumnWidth = Convert.ToInt32(MeasureStringWidth(text, lstFiles.Font.Name, lstFiles.Font.Size));
            }
            catch (Exception)
            {

                throw;
            }
        }
        private void CreateBlankDB(string filename)
        {
            try
            {
                XmlDocument doc = new XmlDocument();
                XmlNode data = doc.CreateNode(XmlNodeType.Element, "Data", string.Empty);
                StaticMethods.MetaField mfinstance = new StaticMethods.MetaField();
                string[] fields = Enum.GetNames(mfinstance.GetType());
                XmlNode item = doc.CreateNode(XmlNodeType.Element, "Item", string.Empty);
                foreach (string myfield in fields)
                {
                    item.Attributes.Append(doc.CreateAttribute(myfield));
                }
                data.AppendChild(item);
                doc.AppendChild(data);

                if (File.Exists(filename))
                    File.Delete(filename);
                doc.Save(filename);
            }
            catch (Exception)
            {

                throw;
            }
        }
        private void CreateDBFromList(ListBox mylist, string dbfield,string filename)
        {
            try
            {
                XmlDocument doc = new XmlDocument();
                XmlNode data = doc.CreateNode(XmlNodeType.Element, "Data", string.Empty);
                StaticMethods.MetaField mfinstance = new StaticMethods.MetaField();
                string[] fields = Enum.GetNames(mfinstance.GetType());

                foreach (object myobj in lstFiles.Items)
                {
                    XmlNode item = doc.CreateNode(XmlNodeType.Element, "Item", string.Empty);
                    foreach (string myfield in fields)
                    {
                        if (myfield.ToLower() != dbfield.ToLower())
                            item.Attributes.Append(doc.CreateAttribute(myfield));
                        else
                            item.Attributes.Append(doc.CreateAttribute(myfield)).InnerText = myobj.ToString();
                    }
                    data.AppendChild(item);
                }
                doc.AppendChild(data);

                if (File.Exists(filename))
                    File.Delete(filename);
                doc.Save(filename);
            }
            catch (Exception)
            {

                throw;
            }
        }
        #endregion
    }
}
